Introduction
This is week 2 assignment of developing data prdoduct course on coursera. Notice that assignment html is based on my blog website which is established by github pages, so the url may seem different.
In this html I want to establish two interactive plots.
First, I will show a financial time series plot with plotly.
Second, I want to make a Chinese map consists 34 provinces with different colors by leaflet and leafletCN packages.
library(tidyverse)
library(leaflet)
library(leafletCN)
library(plotly)Vasicek Model
Vasicek Model is a short interest rate model in finance. The model describes the movement of an interest rate as a factor composed of market risk, time, and equilibrium value, where the rate tends to revert towards the mean of those factors over time. More information in wikipedia
In this part I will simulate 10 different paths of interest rate change defined by Vasicek model. This blog gives me inspiration.
set.seed(42)
## define model parameters
r0 <- 0.03
theta <- 0.10
k <- 0.3
beta <- 0.03
## simulate short rate paths
n <- 10 # MC simulation trials
T <- 10 # total time
m <- 200 # subintervals
dt <- T/m # difference in time each subinterval
r <- matrix(0,m+1,n) # matrix to hold short rate paths
r[1,] <- r0
for(j in 1:n){
for(i in 2:(m+1)){
dr <- k*(theta-r[i-1,j])*dt + beta*sqrt(dt)*rnorm(1,0,1)
r[i,j] <- r[i-1,j] + dr
}
}
r = as.data.frame(r)
r$t = seq(0, T, dt)
vasicek_model = gather(r, paths, dr, -t)
plot_ly(vasicek_model, x = ~t, y = ~dr, color = ~paths, mode = 'line')Chinese Map with leaflet
In this part I want to make a Chinese map consists 34 provinces with different colors by leaflet and leafletCN packages.
if(require(leaflet)){
dat = data.frame(regionNames("china"),
runif(34))
map = leafletGeo("china", dat)
pal <- colorNumeric(
palette = "Blues",
domain = map$value)
leaflet(map) %>% addTiles() %>%
addPolygons(stroke = TRUE,
smoothFactor = 1,
fillOpacity = 0.7,
weight = 1,
color = ~pal(value),
popup = ~htmltools::htmlEscape(popup)
) %>%
addLegend("bottomright", pal = pal, values = ~value,
title = "legendTitle",
labFormat = leaflet::labelFormat(prefix = ""),
opacity = 1)
}